package com.opencover.xterm;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class Xterm {

	private static final File COLOR_REPO_LOCATION = new File("c:/chris/data/repositories/xterm");
	static final File IN_USE_COLOR_FILE = new File(COLOR_REPO_LOCATION, "in-use-color.txt");
	static final File SAVED_COLORS_FILE = new File(COLOR_REPO_LOCATION, "saved-colors.txt");
	static final File TRACE_LOG_FILE = new File(COLOR_REPO_LOCATION, "trace.log");
	static final String XTERM_COLORS_RESOURCE = "xterm-colors.txt";

	private static final String saveAndCreateXtermCommand(ColorPair colorPair) {
		saveColorsInUse(colorPair);
		String xtermCommand = String.format("xterm +tb -fg %s -bg %s", colorPair.getForeground(), colorPair.getBackground());
		trace(String.format("Created command : %s", xtermCommand));
		return xtermCommand;
	}

	private static final void saveColorsInUse(ColorPair colorPair) {
		try {
			FileUtils.writeStringToFile(IN_USE_COLOR_FILE, String.format("%s %s", colorPair.getForeground(), colorPair.getBackground()), false);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private List<String> colors = null;
	private Random randomGenerator = null;

	public Xterm() {
		randomGenerator = new Random();
		try {
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(XTERM_COLORS_RESOURCE);
			colors = IOUtils.readLines(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static final void trace(String line)
	{
		try {
			FileUtils.writeStringToFile(TRACE_LOG_FILE, String.format("%s\n", line), true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public void addLastColors() {
		try {
			ColorPair colorPair = new ColorPair(FileUtils.readFileToString(IN_USE_COLOR_FILE));
			FileUtils.writeStringToFile(SAVED_COLORS_FILE, String.format("%s %s\n", colorPair.getForeground(), colorPair.getBackground()), true);
			trace(String.format("Added colors    : %s", colorPair));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getRandomColor() {
		return colors.get(randomGenerator.nextInt(colors.size()));
	}

	private ColorPair getSavedRandomColors() {
		List<String> savedColors = null;
		try {
			savedColors = FileUtils.readLines(SAVED_COLORS_FILE);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ColorPair(savedColors.get(randomGenerator.nextInt(savedColors.size())));
	}

	public String newTerm() {
		return saveAndCreateXtermCommand(new ColorPair(getRandomColor(), getRandomColor()));
	}

	public String randTerm() {
		return saveAndCreateXtermCommand(getSavedRandomColors());
	}
}
